﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using RuoVea.DynamicWebApi;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar;
using RuoVea.ExSugar.Entity;
using RuoVea.OmiApi.Log.Entitys;
using RuoVea.OmiApi.Log.Service.Dto;
using SqlSugar;
using System.ComponentModel;

namespace RuoVea.OmiApi.Log.Service;

/// <summary>
/// 访问日志服务 🔷
/// </summary>
[ApiExplorerSettings(GroupName = "system")]
public class SysLogVisService : IApplicationService
{
    private readonly SugarRepository<SysLogVis> _thisRepository;

    /// <summary>
    /// 访问日志服务
    /// </summary>
    /// <param name="thisRepository"></param>
    public SysLogVisService(SugarRepository<SysLogVis> thisRepository) => _thisRepository = thisRepository;

    /// <summary>
    /// 分页查询访问日志🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<PageResult<SysLogVisDto>> GetPagesAsync([FromQuery] SysLogVisParam data)
    {
        // 处理结束时间，如果结束时间有值，设置为当天的23:59:59
        DateTime? endTime = data.EndTime;
        if (endTime.HasValue)
        {
            endTime = endTime.Value.Date.AddDays(1).AddSeconds(-1);
        }

        var query = _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(data.Name?.Trim()), u => u.Name.Contains(data.Name.Trim()))
            .WhereIF(!string.IsNullOrEmpty(data.Account?.Trim()), u => u.Account.Contains(data.Account.Trim()))
            .WhereIF(data.VisType.HasValue, u => u.VisType == data.VisType.Value)
            .WhereIF(data.Success.HasValue, u => u.Success == data.Success.Value)
            .WhereIF(data.BeginTime.HasValue, u => u.VisTime >= data.BeginTime.Value)
            .WhereIF(endTime.HasValue, u => u.VisTime <= endTime.Value)
            .OrderByDescending(u => u.VisTime);

        return await query.ToPageAsync<SysLogVis, SysLogVisDto>(data.PageNo, data.PageSize);
    }

    /// <summary>
    /// 根据主键查询🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<SysLogVisDto> GetDataAsync([FromQuery] EntityBaseId data)
    {
        if (data.Id <= 0)
            throw new ArgumentException("无效的ID");

        var model = await _thisRepository.GetByIdAsync(data.Id);
        if (model == null)
            throw new ArgumentException("访问日志记录不存在");

        return model.Adapt<SysLogVisDto>();
    }

    /// <summary>
    /// 删除访问日志🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete("delete")]
    public virtual async Task<bool> DeleteDataAsync([FromBody] EntityBaseId data)
    {
        if (data.Id <= 0)
            throw new ArgumentException("无效的ID");

        return await _thisRepository.DeleteAsync(m => m.Id == data.Id);
    }

    /// <summary>
    /// 清空所有访问日志 🔖
    /// </summary>
    /// <returns></returns>
    [HttpDelete("clear")]
    [DisplayName("清空所有访问日志")]
    public bool Clear()
    {
        return _thisRepository.AsSugarClient().DbMaintenance.TruncateTable<SysLogVis>();
    }

    /// <summary>
    /// 按时间范围删除访问日志
    /// </summary>
    [HttpDelete("clear-by-time")]
    [DisplayName("按时间范围删除访问日志")]
    public async Task<int> ClearByTimeRange([FromQuery] DateTime? beginTime, [FromQuery] DateTime? endTime)
    {
        if (beginTime == null && endTime == null)
            throw new ArgumentException("请至少提供一个时间条件");

        // 处理结束时间
        DateTime? processedEndTime = endTime;
        if (processedEndTime.HasValue)
        {
            processedEndTime = processedEndTime.Value.Date.AddDays(1).AddSeconds(-1);
        }

        return await _thisRepository.AsDeleteable()
            .WhereIF(beginTime.HasValue, u => u.VisTime >= beginTime.Value)
            .WhereIF(processedEndTime.HasValue, u => u.VisTime <= processedEndTime.Value)
            .ExecuteCommandAsync();
    }

    /// <summary>
    /// 批量删除访问日志
    /// </summary>
    [HttpPost("batch-delete")]
    [DisplayName("批量删除访问日志")]
    public async Task<bool> BatchDelete([FromBody] List<long> ids)
    {
        if (ids == null || !ids.Any())
            throw new ArgumentException("请提供要删除的日志ID");

        return await _thisRepository.DeleteAsync(u => ids.Contains(u.Id));
    }

    /// <summary>
    /// 获取登录统计信息（可选添加）
    /// </summary>
    [HttpGet("login-statistics")]
    [DisplayName("获取登录统计信息")]
    public async Task<object> GetLoginStatistics([FromQuery] DateTime? beginTime, [FromQuery] DateTime? endTime)
    {
        // 处理结束时间
        DateTime? processedEndTime = endTime;
        if (processedEndTime.HasValue)
        {
            processedEndTime = processedEndTime.Value.Date.AddDays(1).AddSeconds(-1);
        }

        var query = _thisRepository.AsQueryable()
            .WhereIF(beginTime.HasValue, u => u.VisTime >= beginTime.Value)
            .WhereIF(processedEndTime.HasValue, u => u.VisTime <= processedEndTime.Value);

        var totalCount = await query.CountAsync();
        var successCount = await query.Where(u => u.Success == YesOrNot.Y).CountAsync();
        var failCount = await query.Where(u => u.Success == YesOrNot.N).CountAsync();

        return new
        {
            TotalCount = totalCount,
            SuccessCount = successCount,
            FailCount = failCount,
            SuccessRate = totalCount > 0 ? (double)successCount / totalCount * 100 : 0
        };
    }
}